import struct
import time
class SocketCommunication:
   def recvall(self, conn, n):
      # Helper function to recv n bytes or return None if EOF is hit
      data = b''
      while len(data) < n:
         packet = conn.recv(n - len(data))
         if not packet:
            return None
         data += packet
      return data

   def send_data_bytes(self,conn,content):
       try:
           msg = struct.pack('>I', len(content)) + content
           conn.send(msg)
       except Exception as e:
           print("error happens when sending data in socket tools", e)

   def send_data_str(self,conn, content):
      # Prefix each message with a 4-byte length (network byte order)

      # Send data to the server
      try:
          content = bytes(str(content),encoding="utf-8")
          msg = struct.pack('>I', len(content)) + content
          conn.send(msg)
      except Exception as e:
          print("error happens when sending data in socket tools",e)

   def recv_data_bytes(self, conn):
       # Receive data from the server
       # Return result(an numpy array)
       try:
           resp_len = self.recvall(conn, 4)
           if not resp_len:
               return None
           resp_len = struct.unpack('>I', resp_len)[0]

           if not resp_len:
               return None
           result = self.recvall(conn, resp_len)
       except Exception as e:
           print("error happens in socket utill when receiving data as eval(string)", e)
       return result

   def recv_data_str(self,conn):
      # Receive data from the server
      # Return result(an numpy array)
      try:
          resp_len = self.recvall(conn, 4)
          if not resp_len:
             return None
          resp_len = struct.unpack('>I', resp_len)[0]
          if not resp_len:
             return None
          result = self.recvall(conn, resp_len)
          #result = eval(str(result.decode("utf8")))
      except Exception as e:
          print("error happens in socket utill when receiving data as eval(string)",e)
      return result

